package com.zc.common;

import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * <pre>
 * @File：ClusterVertx
 * @Version：1.0.0
 * @Author：Neil.Zhou
 * @CreateDate：2016/10/4 16:22
 * @Modify：
 * @ModifyDate：2016/9/23
 * @Descript： 集群
 * </pre>
 */
public class ClusterVertx {
    private static Logger logger = LogManager.getLogger(ClusterVertx.class.getName());
    private static Vertx ClusterVertx=null;
    private static Vertx LocalVertx=null;
    private static void setClusterVertx(Vertx vertx,String ipAddress) throws InterruptedException {
        ClusterManager clusterManager = new ZookeeperClusterManager();
        if(ipAddress==null||"".equals(ipAddress)){
            ipAddress= NetworkUtil.getInterface();
        }
        LocalVertx=vertx;
        VertxOptions options = new VertxOptions().setClusterManager(clusterManager).setClusterHost(ipAddress);
        Vertx.clusteredVertx(options, res -> {
            if (res.succeeded()) {
                ClusterVertx =(Vertx) res.result();
                logger.debug("Cluster Successful");
            } else {
                logger.error("Cluster failed: " + res.cause()+";Info:{}","auto retry connection for after  30 seconds ......");
            }
        });
        new Thread().sleep(3*1000);
    }
    private static void rangVertx(Vertx vertx,String ipAddress) {
        if(ClusterVertx==null){
            logger.info("auto retry connection ......");
            try {
                setClusterVertx(vertx,ipAddress);
            } catch (InterruptedException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
    }
    public static Vertx getAfreshClusterVertx(Vertx vertx,String ipAddress) {
        int count=0;
        while(count<5){
            if(ClusterVertx==null){
                rangVertx(vertx,ipAddress);
                count++;
            }else{
                break;
            }
        }
        return ClusterVertx;
    }
    @Deprecated
    public static Vertx getClusterVertx(Vertx vertx) {
        int count=0;
        while(count<5){
            if(ClusterVertx==null){
                rangVertx(vertx,null);
                count++;
            }else{
                break;
            }
        }
        return ClusterVertx;
    }

    public static Vertx getClusterVertx() {
        return ClusterVertx;
    }

    public static Vertx getLocalVertx() {
        return LocalVertx;
    }
}
